package com.hopes.bizz.risk.integral.listener;

import com.hopes.bizz.risk.common.constant.IntegralEventEnum;
import com.hopes.bizz.risk.integral.bo.IntegralEvent;
import com.hopes.boss.common.core.util.SpringContextHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yumr
 * @Description 积分事件监听
 * @time 2023/8/17 17:57
 */
@Component
@RequiredArgsConstructor
public class IntegralEventListener implements InitializingBean {

    private static final Map<String, IntegralEventHandler> integralEventHandlerMap = new HashMap<>();

    @EventListener
    public void handleIntegralEvent(IntegralEvent integralEvent) {
        if (null == integralEvent || !IntegralEventListener.contains(integralEvent.getModule())) {
            return;
        }
        IntegralEventListener.getIntegralEventHandler(integralEvent.getModule()).handler(integralEvent);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        integralEventHandlerMap.putAll(SpringContextHolder.getBeansOfType(IntegralEventHandler.class));
    }

    private static boolean contains(IntegralEventEnum eventEnum) {
        if (null== eventEnum) {
            return false;
        }
        return integralEventHandlerMap.containsKey(eventEnum.name());
    }

    private static IntegralEventHandler<?> getIntegralEventHandler(IntegralEventEnum eventEnum) {
        return integralEventHandlerMap.get(eventEnum.name());
    }
}
